#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#define LOG "log.txt"

int main()
{
    umask(0);
    //int fd = open(LOG, O_CREAT | O_WRONLY | O_APPEND, 0666);//追加写入
    //int fd = open(LOG, O_CREAT | O_WRONLY | O_TRUNC, 0666);//打开/创建文件+只写+清空
    int fd = open(LOG, O_RDONLY);//只读
    if(fd == -1)
    {
        printf("fd: %d, errno: %d, errstring: %s\n", fd, errno, strerror(errno));
    }
    else
    {
        printf("fd: %d, errno: %d, errstring: %s\n", fd, errno, strerror(errno));
    }

    char buffer[1024];

    ssize_t n = read(fd, buffer, sizeof(buffer)-1);//sizeof会计算\0,IO操作都不算\0，记得-1
    if(n > 0)
    {
        buffer[n] = '\0';
        printf("%s", buffer);
    }
    //const char *str = "hello world!";
    //int cnt = 5;
    //while(cnt)
    //{
    //    char line[128];
    //    snprintf(line, sizeof(line), "%s, %d\n", str, cnt);
    //    write(fd, line, strlen(line));//strlen不计算\0，但是这里不+1，因为\0是C语言的规定，不是文件的规定！！
    //    cnt--;
    //}
    close(fd);
    return 0;
}












/*#define ONE 0x1
#define TWO 0x2
#define THREE 0x4
#define FOUR 0x8
#define FIVE 0x10

void Print(int flag)
{
    if(flag & ONE) printf("ONE\n");
    if(flag & TWO) printf("TWO\n");
    if(flag & THREE) printf("THREE\n");
    if(flag & FOUR) printf("FOUR\n");
    if(flag & FIVE) printf("FIVE\n");
}

int main()
{
    Print(ONE);
    Print(TWO);
    Print(THREE);
    Print(FOUR);
    Print(FIVE);
    printf("----------\n");
    Print(ONE|TWO);
    printf("----------\n");
    Print(ONE|TWO|THREE);
    printf("----------\n");
    return 0;
}






/*
#define LOG "log.txt"

int main()
{
    FILE *fp = fopen(LOG, "r");
    if(fp == NULL)
    {
        perror("fopen");
        return 1;
    }

    //const char *str = "hello world!";
    //int cnt = 5;
    while(cnt)
    {
        char buffer[256];
        snprintf(buffer, sizeof(buffer), "%s:%d\n", str, cnt);
        printf("%s", buffer);
        //fprintf(fp, "%d: YGH: %s\n", cnt, str);
        cnt--;
    }

    const char *str = "hello world!\n";
    int cnt = 5;
    while(cnt--)
    {
        fputs(str, fp);
    }
    char buffer[128];
    while(1)
    {
        if(fgets(buffer, sizeof(buffer), fp) == NULL)
        {
            break;
        }
        else
        {
            printf("%s", buffer);
        }
    }


    fclose(fp);
    return 0;
} 
*/